/**
 * Copyright (c) 2015-2018, Michael Yang 杨福海 (fuhai999@gmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.hg.base.kit;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jfinal.core.JFinal;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;

public class StrExtKit extends StrKit {

	private static final Log log = Log.getLog(StrExtKit.class);

	public static String clearSpecialCharacter (String string) {

		if (StrKit.isBlank(string)) {
			return string;
		}

		/**
		 * P：标点字符； L：字母； M：标记符号（一般不会单独出现）； Z：分隔符（比如空格、换行等）； S：符号（比如数学符号、货币符号等）；
		 * N：数字（比如阿拉伯数字、罗马数字等）； C：其他字符
		 */
		// return string.replaceAll("[\\pP\\pZ\\pM\\pC]", "");
		return string.replaceAll("[\\\\\'\"\\/\f\n\r\t]", "");
	}

	public static String escapeHtml (String text) {

		if (StrKit.isBlank(text)) {
			return text;
		}

		return text.replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;").replace("'", "&#x27;")
			.replace("/", "&#x2F;");
	}

	/**
	 * 生成流水号
	 *
	 * @param uuid
	 *            谋订单的主键ID
	 *
	 * @return
	 */
	public static String generateSerialNumber (String uuid) {
		return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + Math.abs(uuid.hashCode());
	}

	/**
	 * 生成验证码
	 */
	public static String getValidateCode () {
		Random random = new Random();
		return String.valueOf(random.nextInt(9999 - 1000 + 1) + 1000);// 为变量赋随机值1000-9999
	}

	/***
	 * 驼峰命名转为下划线命名
	 *
	 * @param para
	 *            驼峰命名的字符串
	 */
	public static String humpToUnderline (String para) {

		if (null == para) {
			return null;
		}

		StringBuilder sb = new StringBuilder(para);
		int temp = 0;// 定位

		for (int i = 0; i < para.length(); i++) {

			if (Character.isUpperCase(para.charAt(i))) {
				sb.insert(i + temp, "_");
				temp += 1;
			}

		}

		return sb.toString().toLowerCase();
	}

	public static boolean isEmail (String email) {
		return Pattern.matches("\\w+@(\\w+.)+[a-z]{2,3}", email);
	}

	public static boolean isMobileNumber (String phoneNumber) {
		return Pattern.matches("^(1[3,4,5,7,8])\\d{9}$", phoneNumber);
	}

	public static boolean isNumeric (String str) {

		if (str == null) {
			return false;
		}

		for (int i = str.length(); --i >= 0;) {
			int chr = str.charAt(i);

			if (chr < 48 || chr > 57) {
				return false;
			}

		}

		return true;
	}

	public static boolean match (String string, String regex) {
		Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(string);
		return matcher.matches();
	}

	public static Set<String> splitToSet (String src, String regex) {

		if (src == null) {
			return null;
		}

		String[] strings = src.split(regex);
		Set<String> set = new HashSet<>();

		for (String table : strings) {

			if (StrKit.isBlank(table)) {
				continue;
			}

			set.add(table.trim());
		}

		return set;
	}

	public static BigInteger toBigInteger (String value, BigInteger defaultValue) {

		try {

			if (value == null || "".equals(value.trim())) {
				return defaultValue;
			}

			value = value.trim();

			if (value.startsWith("N") || value.startsWith("n")) {
				return new BigInteger(value).negate();
			}

			return new BigInteger(value);
		}
		catch (Exception e) {
			StrExtKit.log.error("toBigInteger is error", e);
		}

		return defaultValue;
	}

	public static int toInt (String value, int defaultValue) {

		try {

			if (value == null || "".equals(value.trim())) {
				return defaultValue;
			}

			value = value.trim();

			if (value.startsWith("N") || value.startsWith("n")) {
				return -Integer.parseInt(value.substring(1));
			}

			return Integer.parseInt(value);
		}
		catch (Exception e) {
			StrExtKit.log.error("toInt is error", e);
		}

		return defaultValue;
	}

	public static long toLong (String value, Long defaultValue) {

		try {

			if (value == null || "".equals(value.trim())) {
				return defaultValue;
			}

			value = value.trim();

			if (value.startsWith("N") || value.startsWith("n")) {
				return -Long.parseLong(value.substring(1));
			}

			return Long.parseLong(value);
		}
		catch (Exception e) {
			StrExtKit.log.error("toLong is error", e);
		}

		return defaultValue;
	}

	public static String urlDecode (String string) {

		try {
			return URLDecoder.decode(string, JFinal.me().getConstants().getEncoding());
		}
		catch (UnsupportedEncodingException e) {
			StrExtKit.log.error("urlDecode is error", e);
		}

		return string;
	}

	public static String urlEncode (String string) {

		try {
			return URLEncoder.encode(string, JFinal.me().getConstants().getEncoding());
		}
		catch (UnsupportedEncodingException e) {
			StrExtKit.log.error("urlEncode is error", e);
		}

		return string;
	}

	public static String urlRedirect (String redirect) {

		try {
			redirect = new String(redirect.getBytes(JFinal.me().getConstants().getEncoding()), "ISO8859_1");
		}
		catch (UnsupportedEncodingException e) {
			StrExtKit.log.error("urlRedirect is error", e);
		}

		return redirect;
	}

	public static String uuid () {
		return UUID.randomUUID().toString().replace("-", "");
	}

}
